package com.cslg.ac.demo.controller.donate;

import com.cslg.ac.demo.constant.ResponseCode;
import com.cslg.ac.demo.entity.donate.Donation;
import com.cslg.ac.demo.entity.user.User;
import com.cslg.ac.demo.service.donate.DonateService;
import com.cslg.ac.demo.util.communicate.ResponseUtil;
import org.omg.CORBA.OBJECT_NOT_EXIST;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

@Controller
public class DonateController {
    @Autowired
    DonateService donateService;


    @RequestMapping(value = "/donate/getInfo")
    public void getInfo(@RequestParam int id, PrintWriter out){
        Donation donation;
        try {
            donation = donateService.getInfo(id);
        }catch (Exception e) {
            e.printStackTrace();
            ResponseUtil.responseCode(out, ResponseCode.SERVER_ERROR);
            return;
        }
        Map<String,Object> param = new HashMap<>(1);
        param.put("donation", donation);
        ResponseUtil.response(out, ResponseCode.REQUEST_SUCCESSED, param);

    }

    @RequestMapping(value = "/donate/donateCard", method = RequestMethod.POST)
    public void donateCard(Donation donation, HttpSession session, PrintWriter out){
        User user = (User)session.getAttribute("user");
        if(!donation.insertValid()){
            ResponseUtil.responseCode(out, ResponseCode.PARAM_ILLEGAL);
            return;
        }
        donation.setUserId(user.getId());
        int code;
        try {
            code = donateService.donateCard(donation);
        }catch (Exception e) {
            e.printStackTrace();
            ResponseUtil.responseCode(out, ResponseCode.SERVER_ERROR);
            return;
        }
        ResponseUtil.responseCode(out, code);
    }
}
